package com.note.back.controller;

import com.note.back.pojo.Note;
import com.note.back.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@RestController
public class FileDownloadController {
    @Autowired
    NoteService noteService;
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> downloadNote(@PathVariable String id) {
        Note note = noteService.findById(Integer.valueOf(id));

        if (note == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        // 生成MD格式的内容
        String mdContent = generateMdContent(note);

        // 将内容转换为字节数组
        byte[] contentBytes = mdContent.getBytes(StandardCharsets.UTF_8);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", note.getName() + ".md");

        return new ResponseEntity<>(contentBytes, headers, HttpStatus.OK);
    }

    private String generateMdContent(Note note) {
        StringBuilder mdBuilder = new StringBuilder();
        mdBuilder.append("# ").append(note.getName()).append("\n\n");
        mdBuilder.append("**描述**：").append(note.getDescription()).append("\n\n");
        mdBuilder.append(note.getContentMd());
        return mdBuilder.toString();
    }
}